package web0

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	config0 "searcher/src/config"
	router0 "searcher/src/router"
	"syscall"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

type NormalServer struct{}

var (
	sc   config0.SimpleConfig
	port = sc.GetPort()
)

// start web server
func (m *NormalServer) Start(flag bool) {

	if flag {
		// gin.DebugMode , ReleaseMode
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	app := gin.Default()

	// 跨域
	app.Use(cors.Default())

	// 路由
	var router router0.WebRouters
	router.AllRouters(app)

	// http server
	srv := &http.Server{
		Addr:    ":" + port,
		Handler: app,
	}

	// 启动服务
	go func() {
		log.Printf("Web服务将启动在 %s 端口，本地请访问 http://localhost:%s\n", port, port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Web服务启动失败, %v\n", err)
		}
	}()

	// 停止
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, syscall.SIGTERM)

	for val := range quit {
		_ = val
		m.shutdown(srv)
		break
	}
}

// server shutdown
func (m *NormalServer) shutdown(srv *http.Server) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("web server stop throw error : %s\n", err)
	}

	log.Println("web server stop ...")
}
